<template>
  <div class="user-info">
    <div class="avatar-box" @click="handleAvatarClick">
      <img class="avatar" :src="user.avatar" alt="avatar" />
      <span class="nickname">{{ user.nickname }}</span>
      <svg class="arrow" width="16" height="16" viewBox="0 0 16 16"><path d="M4 6l4 4 4-4" stroke="#2563eb" stroke-width="2" fill="none" stroke-linecap="round"/></svg>
    </div>
    <div v-if="showMenu" class="dropdown-menu">
      <div class="menu-item" @click="logout">退出登录</div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/store/user'
import { getUserInfo } from '@/api/user'

const userStore = useUserStore()
const user = ref({
  nickname: '',
  avatar: ''
})
const showMenu = ref(false)
const hasLoadedUserInfo = ref(false)

async function fetchUserInfo() {
  const localUser = localStorage.getItem('user')
  if (!localUser) {
    console.warn('localStorage 里没有 user 字段，未登录或未保存用户信息')
    return
  }
  let userId
  try {
    const parsedUser = JSON.parse(localUser)
    userId = parsedUser && parsedUser.id
    if (parsedUser.avator && !parsedUser.avatar) {
      parsedUser.avatar = parsedUser.avator
    }
  } catch (e) {
    userId = undefined
  }
  console.log('最终 userId', userId)
  if (!userId) return
  const res = await getUserInfo(userId)
  user.value = res.data ? res.data : res
  userStore.setUser(user.value)
  hasLoadedUserInfo.value = true
}

function handleAvatarClick() {
  toggleMenu()
  if (!hasLoadedUserInfo.value) {
    fetchUserInfo()
  }
}

function toggleMenu() {
  showMenu.value = !showMenu.value
}
function logout() {
  showMenu.value = false
  userStore.logout()
  window.location.href = '/login'
}

onMounted(() => {
  // fetchUserInfo()
})
</script>
<style scoped>
.user-info {
  position: relative;
  display: flex;
  align-items: center;
  cursor: pointer;
}
.avatar-box {
  display: flex;
  align-items: center;
  background: #f6faff;
  border-radius: 20px;
  padding: 6px 18px 6px 8px;
  box-shadow: 0 2px 8px 0 rgba(120, 160, 255, 0.06);
  border: 1px solid #e3eaf5;
  transition: box-shadow 0.18s;
}
.avatar-box:hover {
  box-shadow: 0 4px 16px 0 rgba(120, 160, 255, 0.12);
}
.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin-right: 10px;
  border: 2px solid #e3eaf5;
  background: #fff;
}
.nickname {
  font-size: 16px;
  color: #2563eb;
  font-weight: 500;
  margin-right: 6px;
}
.arrow {
  transition: transform 0.18s;
}
.dropdown-menu {
  position: absolute;
  right: 0;
  top: 54px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 24px 0 rgba(120, 160, 255, 0.13);
  border: 1px solid #e3eaf5;
  min-width: 120px;
  z-index: 10;
  padding: 8px 0;
}
.menu-item {
  padding: 10px 20px;
  color: #2563eb;
  font-size: 15px;
  cursor: pointer;
  transition: background 0.15s;
}
.menu-item:hover {
  background: #e3edfa;
}
</style>
